using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Collections.Generic;
using System.Collections;

namespace Commonplace
{
	/// <summary>
	/// Summary description for StoredConfig.
	/// </summary>
	public class StoredConfig
	{
		XmlDocument _config;
        Dictionary<string, List<string>> _lists = new Dictionary<string, List<string>>();

        public List<string> GetList(string name)
        {
            if (true == _lists.ContainsKey(name))
                return _lists[name];

            XmlElement listNode = _config.SelectSingleNode(string.Format("/config/list[@name='{0}']", name)) as XmlElement;

            if (null == listNode)
                return new List<string>();

            List<string> list = new List<string>();
            foreach (XmlElement listItemNode in listNode.SelectNodes("./item"))
            {
                list.Add(listItemNode.InnerText);
            }

            return list;
        }

        public void UpdateList(string name, List<string> list)
        {
            if (false == _lists.ContainsKey(name))
                _lists[name] = list;

            XmlElement listNode = _config.SelectSingleNode(string.Format("/config/list[@name='{0}']", name)) as XmlElement;

            if (null == listNode)
            {
                listNode = _config.CreateElement("list");
                _config.DocumentElement.AppendChild(listNode);
            }

            listNode.RemoveAll();
            listNode.SetAttribute("name", name);

            foreach (string item in list)
            {
                XmlElement listItemNode = _config.CreateElement("item");
                listItemNode.InnerText = item;
                listNode.AppendChild(listItemNode);
            }
            
        }

		public string this[string name]
		{
			get
			{
				XmlNode node = _config.SelectSingleNode("/config/param[@name='" + name + "']");
				if (null != node)
				{
					return node.Attributes["value"].InnerText;
				}
				else
					return string.Empty;
			}
			set
			{
				XmlNode node = _config.SelectSingleNode("/config/param[@name='" + name + "']");
				if (null != node)
				{
					if (value != null)
						node.Attributes["value"].InnerText = value;
					else
						node.ParentNode.RemoveChild(node);
				}
				else
				{
					if (value != null)
					{
						XmlNode newNode = _config.CreateNode(XmlNodeType.Element,"param","");
						newNode.Attributes.Append(_config.CreateNode(XmlNodeType.Attribute, "name","") as XmlAttribute);
						newNode.Attributes.Append(_config.CreateNode(XmlNodeType.Attribute, "value","") as XmlAttribute);
						newNode.Attributes["name"].InnerText = name;
						newNode.Attributes["value"].InnerText = value;
						_config.DocumentElement.AppendChild(newNode);
					}
				}
			}
		}

		public StoredConfig()
		{
			_config = TryLoadConfig();
		}

        public bool HasSavedConfiguration
        {
            get
            {
                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForAssembly();

                try
                {
                    IsolatedStorageFileStream fs = new IsolatedStorageFileStream("prefs.xml", FileMode.Open, iso);
                    fs.Close();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

		private XmlDocument TryLoadConfig()
		{
			IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForAssembly();

			try
			{
				IsolatedStorageFileStream fs = new IsolatedStorageFileStream("prefs.xml", FileMode.Open, iso);
				XmlDocument doc = new XmlDocument();
				doc.Load(fs);
				fs.Close();
				return doc;
			}
			catch (IOException)
			{
				XmlDocument doc = new XmlDocument();
				doc.AppendChild(doc.CreateNode(XmlNodeType.Element, "config", ""));
				return doc;
			}
			finally
			{
				iso.Dispose();
			}
		}

		public void Save()
		{
			IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForAssembly();
			try
			{
				IsolatedStorageFileStream fs = new IsolatedStorageFileStream("prefs.xml", FileMode.Create, iso);

				_config.Save(fs);

				fs.Close();
			}
			finally
			{
				iso.Dispose();
			}
		}

			
	}
}
